package com.yugu.park.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.yugu.enums.HttpCode;
import com.yugu.util.ResponseUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public ResponseUtil.Result<String> exceptionHandler(HttpServletRequest request, Exception e) {
        if (e instanceof MethodArgumentNotValidException) {
            return ResponseUtil.addError(((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage());
        }
        //绑定异常是需要明确提示给用户的
        else if (e instanceof BindException) {
        	log.debug("aa");
            BindException exception = (BindException) e;
            List<ObjectError> errors = exception.getAllErrors();
            String msg = errors.get(0).getDefaultMessage();//获取自错误信息
            return ResponseUtil.addError(msg);//将具错误信息设置到CodeMsg中返回
        }
// 其余异常简单返回为服务器异常
        return ResponseUtil.addError(e.getMessage());

    }

    @ExceptionHandler({BizException.class})
    public ResponseUtil.Result<?> handle(BizException exception) {
        return ResponseUtil.addCustom(HttpCode.WX_ERROR.value(), exception.getMessage());
    }
    @ExceptionHandler({BusinessException.class})
    public ResponseUtil.Result<?> handle(BusinessException exception) {
        return ResponseUtil.addCustom(HttpCode.CONFLICT.value(), exception.getMessage());
    }
}
